package com.yunshang.shoppingmall.shopping.WeChat.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yunshang.shoppingmall.common.HttpRequest;
import com.yunshang.shoppingmall.common.ImageUtil;
import com.yunshang.shoppingmall.common.QRCodeUtil;
import com.yunshang.shoppingmall.common.weixin.WeChat;
import com.yunshang.shoppingmall.entity.MergeImage;
import com.yunshang.shoppingmall.shopping.WeChat.entity.Ticket;
import com.yunshang.shoppingmall.shopping.WeChat.entity.Token;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class WinxinUtil {

    public static String getToken(String appid, String appsecret) {
        String accessToken = "";
//        System.out.println(WinChat.access_token);
        if(WinChat.access_token!=null && !WinChat.access_token.equals(""))
        {
//            System.out.println("A");
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR, -1);// 24小时制
            Date date = cal.getTime();

//            System.out.println("过期时间："+date.toString());

            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(WinChat.access_token_time);

//            System.out.println("获取时间："+cal1.getTime().toString());
//
//            System.out.println("比较："+date.before(cal1.getTime()));

            if(date.before(cal1.getTime()))
            {
                return WinChat.access_token;
            }
        }
        System.out.println("B");
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        System.out.println(tokenUrl);
        String tokenRes = HttpRequest.getHttp(tokenUrl);
        if (tokenRes != null) {
            System.out.println(tokenRes);

            try {
                //将接收到的数据转化为对象
                Token token = JSON.parseObject(tokenRes, new TypeReference<Token>() {
                });

                if (token.getAccess_token() != null) {
                    accessToken = token.getAccess_token();
                    WinChat.access_token = accessToken;
                    WinChat.access_token_time = new Date();
                }

            } catch (Exception ex) {
            }
        }

        System.out.println("调用一次："+accessToken);

        return accessToken;
    }

    public static String getTicket(String access_token, String scene_str) {

        String urlTicket = "";

        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
        System.out.println(url);
        String par = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + scene_str + "\"}}}";
        System.out.println(par);
        String res = HttpRequest.sendPost(url, par);
        System.out.println(res);
        try {
            //将接收到的数据转化为对象
            Ticket ticket = JSON.parseObject(res, new TypeReference<Ticket>() {
            });

            if (ticket.getUrl() != null) {
                urlTicket = ticket.getUrl();
            }

        } catch (Exception ex) {
        }
        return urlTicket;
    }

    public static String getEWM(String url, String logoImgURL, String imgURL, String x, String y) {

        //本地
       // File path = new File("E:/images/uploads/");

        //服务器
        File path = new File("/usr/local/mall_uploads/");

        if (!path.exists()) {
            path.mkdirs();
        }

        String logoUrl = path + logoImgURL;
        String erWMImgUrl = path + "/";
        try {
            //生成二维码
            String urlQrcode = QRCodeUtil.encode(url, logoUrl, erWMImgUrl, true);

            //添加背景图片
            String bgImg = path + imgURL;//背景图路径
            System.out.println("背景图路径：" + bgImg);

            //输出图片地址
            String uuId = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
            String outImg = path + "/ewm_w_" + uuId + ".png";
            System.out.println("输出图片地址:" + outImg);

            FileInputStream fis = new FileInputStream(bgImg);
            FileOutputStream out = new FileOutputStream(outImg);
            int n = 0;
            byte[] buff = new byte[1024];
            while ((n = fis.read(buff)) != -1) {
                out.write(buff, 0, n);
            }
            out.close();
            fis.close();

            //合成图片--背景图片和二维码合成
            MergeImage.mergeImage(outImg, urlQrcode, x, y);

            return uuId+".png";
        } catch (Exception ex) {
            return null;
        }
    }

    public static String getEWMU(String url, String logoImgURL, String imgURL, String x, String y) {

        //本地
        //File path = new File("E:/images/uploads/");

        //服务器
        File path = new File("/usr/local/mall_uploads/");

        if (!path.exists()) {
            path.mkdirs();
        }

        String logoUrl = path + logoImgURL;
        String erWMImgUrl = path + "/";
        try {
            //生成二维码
            String urlQrcode = QRCodeUtil.encode(url, logoUrl, erWMImgUrl, true);

            if(ImageUtil.zoomInImage(urlQrcode,urlQrcode,1.7)) {
                //添加背景图片
                String bgImg = path + imgURL;//背景图路径
                System.out.println("背景图路径：" + bgImg);

                //输出图片地址
                String uuId = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
                String outImg = path + "/ewm_w_" + uuId + ".png";
                System.out.println("输出图片地址:" + outImg);

                FileInputStream fis = new FileInputStream(bgImg);
                FileOutputStream out = new FileOutputStream(outImg);
                int n = 0;
                byte[] buff = new byte[1024];
                while ((n = fis.read(buff)) != -1) {
                    out.write(buff, 0, n);
                }
                out.close();
                fis.close();

                //合成图片--背景图片和二维码合成
                MergeImage.mergeImage(outImg, urlQrcode, x, y);

                return "/ewm_w_"+uuId + ".png";
            }
            return null;
        } catch (Exception ex) {
            return null;
        }
    }

    /***
     * 发送模板消息
     * @param txtJson 关键词
     * @param openId  OpenID
     * @param template_id 模板ID
     * @param url  消息链接
     * @return
     */
    public static Boolean sendMessage(String txtJson,String openId,String template_id,String url) {
        String access_token = WinxinUtil.getToken(WinChat.appid, WinChat.appsecret);
        if (access_token != "") {
            String sendUrl = WinChat.Send_URL;
            sendUrl = sendUrl.replace("ACCESS_TOKEN", access_token);

            String parJosn = "{\"touser\":\"" + openId + "\",\"template_id\":\"" + template_id + "\",\"url\":\"" + url + "\",\"data\":{" + txtJson + "}}";

            String html = HttpRequest.sendPost(sendUrl, parJosn);
            System.out.println(html);
            if (html.contains("\"errmsg\":\"ok\"")) {
                return true;
            }
        }
        return false;
    }
}
